/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.sunspotworld.power;

import com.sun.spot.peripheral.Battery;
import com.sun.spot.peripheral.Spot;
import org.sunspotworld.StartApplication;
import org.sunspotworld.datawrappers.DataWrapperVector;
import org.sunspotworld.mydatawrappers.PowerPacket;
import org.sunspotworld.sensortasks.SensorTask;

/**
 *
 * @author me
 */
public class PowerShutdownListener extends SensorTask {
    private static Battery batt = (Battery)Spot.getInstance().getPowerController().getBattery();
    private static double lastReading = batt.getAvailableCapacity();

    public PowerShutdownListener(long time) {
        super.sampleInterval = time;
        if (batt.getBatteryLevel() > 50) {
            Spot.getInstance().setPersistentProperty("PowerDown", "false");
        }
    }
    
    private PowerShutdownListener(long time, long iden) {
        super.sampleInterval = time;
        super.id = iden;
    }
    
    protected SensorTask copy() {
        return new PowerShutdownListener(super.sampleInterval, super.id);
    }

    public void runTask() {
        double reading = batt.getAvailableCapacity();
        DataWrapperVector.getInstance().add(new PowerPacket(reading));
        if (batt.getAvailableCapacity() < (reading - lastReading)+DataWrapperVector.getInstance().shutDownPowerNeeded()) {
            Spot.getInstance().setPersistentProperty("PowerDown", "true");
            DataWrapperVector.getInstance().add(new PowerPacket(-5));
            StartApplication.getMIDlet().notifyDestroyed();
        } 
        lastReading = reading;
    }
    
    
}
